package com.example.cpsc.sc.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.naming.AuthenticationException;


//Security分两部分认证和授权
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/post","/home","/css/**","/js/**","/img/**").permitAll()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限默认到登陆界面
        http.formLogin().loginPage("/Tologin").usernameParameter("username").passwordParameter("password");

        //注销之后跳转到的界面
        http.logout().logoutSuccessUrl("/logout");

        //记住登录用户的信息，下次可以该用户直接进入，保存信息14天
        http.rememberMe().rememberMeParameter("rememberMe");
    }
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        //数据中认证  auth.jdbcAuthentication()
        //内存认证
        //PasswordEncoder密码编码必须加密
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("cuipeng").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }

}
